package com.example.server.plugins.routing

import com.example.server.db.dao.UserDao
import com.example.commons.models.User
import io.ktor.http.*
import io.ktor.resources.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.resources.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.routing.post
import kotlinx.serialization.Serializable
import org.slf4j.Logger
import org.slf4j.LoggerFactory


private val logger: Logger = LoggerFactory.getLogger("User")

/**
 * 用户路由配置
 */
fun Route.configUserRouting() {
    get<UserRoute.Page> { u ->
        val lists = UserDao.getInstance().page(u.page, u.size)
        call.respond(lists)
    }

    post("/users") {
        val user = call.receive<User>()
        logger.info(user.toString())
        val ar = UserDao.getInstance().insert(user)
        if (ar == null) {
            call.respondText("created failed!")
        } else {
            call.respond(HttpStatusCode.Created, ar)
        }
    }
}


@Serializable
@Resource("/users")
private class UserRoute() {

    @Serializable
    @Resource("")
    data class Page(val parent: UserRoute = UserRoute(), val page: Int = 1, val size: Int = 30)

}